<template>
    <div class="supervision_map flex-column">
        <div class="statistics_box flex-row">
            <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_scheme_all" />
                <div class="content flex-column">
                    <span class="num">{{ baseInfo.totalSize || 0 }}</span>
                    <span class="label">施工总数</span>
                </div>
            </div>
            <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_unscheme_start" />
                <div class="content flex-column">
                    <span class="num">{{ baseInfo.notStartSize || 0 }}</span>
                    <span class="label">未施工开始</span>
                </div>
            </div>
            <!-- <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_undo_warning" />
                <div class="content flex-column">
                    <span class="num">20</span>
                    <span class="label">未处理告警</span>
                </div>
            </div> -->
            <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_unrectify" />
                <div class="content flex-column">
                    <span class="num">{{ baseInfo.correctSize || 0 }}</span>
                    <span class="label">待整改工单</span>
                </div>
            </div>
            <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_scheme_person" />
                <div class="content flex-column">
                    <span class="num">{{ baseInfo.memberSize || 0 }}</span>
                    <span class="label">施工人员</span>
                </div>
            </div>
            <div class="statistic_item flex-row">
                <svg-icon class="icon" icon="statistics_delay" />
                <div class="content flex-column">
                    <span class="num">{{ baseInfo.delaySize || 0 }}</span>
                    <span class="label">延期施工</span>
                </div>
            </div>
        </div>

        <div class="map_right_side flex-column">
            <div class="side_item flex-row" @click="isWeather = !isWeather">
                <span class="info"
                    >{{ liveWeather.province }}{{ liveWeather.city }}<br />{{ liveWeather.weather }} |
                    {{ liveWeather.temperature }}°C</span
                >
                <!-- <iframe scrolling="no" color="#fff" src="https://tianqiapi.com/api.php?style=ye&skin=pitaya" frameborder="0" width="100%" height="60" allowtransparency="true"></iframe> -->
                <a-icon v-if="isWeather" type="up" />
                <a-icon v-else type="down" />
            </div>
            <div class="weather_box" style="background-color: #fff;" v-show="isWeather">
                <iframe
                    scrolling="no"
                    src="https://tianqiapi.com/api.php?style=ts&skin=gif"
                    frameborder="0"
                    width="325"
                    height="220"
                    allowtransparency="true"
                ></iframe>
            </div>
            <div class="side_item flex-row" @click="isCity = !isCity">
                <span class="info">全国</span>
                <a-icon v-if="isCity" type="up" />
                <a-icon v-else type="down" />
            </div>
            <div class="city_modal" v-show="isCity">
                <a-select
                    show-search
                    placeholder="请选择城市"
                    option-filter-prop="children"
                    style="width: 190px"
                    allowClear
                    v-model="city"
                    :filter-option="filterOption"
                >
                    <a-select-option :value="city.dictValue" v-for="city in dict.city" :key="city.dictKey">{{
                        city.dictValue
                    }}</a-select-option>
                </a-select>
            </div>
        </div>

        <div class="menu_box flex-row">
            <div
                :class="['menu_item flex-column', item.active && 'active']"
                v-for="(item, index) in menuBox"
                :key="index"
                @click="switchStatus(item, index)"
            >
                <svg-icon class="icon" :icon="item.icon" />
                <span class="label">{{ item.label }}</span>
            </div>
        </div>
        <div id="container" class="super_amap flex-column"></div>
    </div>
</template>
<script>
import { getCache } from '@/utils/session';
import { getStatistics, getMapStatistics } from '@/api/supervision/map';
import { mapState } from 'vuex';
import axios from 'axios';
import mapWeather from './components/map-weather.vue';

export default {
    components: { mapWeather },
    name: 'SupervisionMap',
    dicts: ['city'],
    data() {
        let self = this;
        let userInfo = getCache('userInfo') || { userId: '' };
        let { userId } = userInfo;
        return {
            userId,
            roadIcon: require('@/assets/map/scheme.png'),
            loading: true,
            status: '',
            city: undefined,
            baseInfo: {},
            map: null,
            menuBox: [
                // {
                //     icon: 'menu_road',
                //     label: '路段',
                //     active: false
                // },
                {
                    icon: 'menu_unstart',
                    label: '未施工',
                    active: false
                },
                {
                    icon: 'menu_doing',
                    label: '施工中',
                    active: true
                },
                {
                    icon: 'menu_timeout',
                    label: '超时',
                    active: false
                },
                {
                    icon: 'menu_unrectify',
                    label: '待整改',
                    active: false
                },

                {
                    icon: 'menu_sucsess',
                    label: '已完成',
                    active: false
                }
            ],
            labelMarkerList: [],
            lineList: [],
            roadList: [],
            markerList: [],
            isWeather: false,
            isCity: false,
            timer: null,
            key: '0a6447eb39596684e4bcdf8b949e797a',
            liveWeather: {}
        };
    },
    computed: {
        ...mapState({
            userArea: state => state.user.userArea
        })
    },
    watch: {
        city: function() {
            this.clearMapMarker();
            this.getMapList('');
        }
    },
    created() {
        this.getAmapWeather();
        this.getBaseInfo();
    },
    async mounted() {
        await this.initMap();
        this.getMapList('施工中')
    },
    methods: {
        clearMapMarker() {
            this.markerList.map(marker => {
                this.map.remove(marker);
            });
            this.labelMarkerList.map(item => {
                this.map.remove(item);
            });
            this.lineList.map(item => {
                this.map.remove(item);
            });
            this.roadList = [];
            this.markerList = [];
            this.labelMarkerList = [];
        },
        //切换状态
        async switchStatus(item, index) {
            let { label, active } = item;
            this.clearMapMarker();
            item.active = !active;
            let activeLabels = [];
            this.menuBox.map(menu => {
                if (menu.active) {
                    activeLabels.push(menu.label);
                }
            });
            let activeLabelString = activeLabels.join(',') || null;
            this.getMapList(activeLabelString);
        },
        initMap() {
            try{
                var map = new AMap.Map('container', {
                    zoom: 13,
                    showLabel: true,
                    expandZoomRange: true,
                    // center: [116.12, 39.11],
                    // viewMode: '3D',
                    pitch: 60,
                    mapStyle: 'amap://styles/whitesmoke'
                });
                this.searchCity();
                this.map = map;
                this.status = '';
            }catch(err){
                console.log(err)
                location.reload();
            }
        },
        //添加路标
        createMarker({ name, id, lng, lat, status,type }) {
            let location = this.getLabelImage(type,status);
            let content = `<div class="road_label_marker ${status}">
                   <div class="marker_item">
                    <p>${name}</p>
                    <span class="arrow"></span>
                   </div>
                   <img class="location" src="${location}"/>
                </div>`;
            var marker = new AMap.Marker({
                markerId: id,
                position: [lng, lat],
                // 将 html 传给 content
                content: content,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-18, -52),
                zIndex: 999
            });
            marker.on('click', ()=>{
                let content = ``;
                var infoWindow = new AMap.InfoWindow({
                    position: [lng,lat],
                    offset: new AMap.Pixel(0, -52),
                    content: `<div>
                            <h3 class="title" style='color:#d84447'>${name}</h3>
                            <p class="desc">类型：${type=='01'?'互通':(type=='02'?'隧道':'特殊路段')}</p>
                            <p class="desc">桩号：${name}</p>
                            <p class="desc">经纬度：${lng}、${lat}</p>
                        </div>`
                });
                infoWindow.open(this.map);
            });
            this.map.add(marker);
            this.markerList.push(marker);
            this.map.setFitView();
        },
        //根据道路类型和状态切换图片
        getLabelImage(type,status){
            let roadName = type=='01'?'interflow':(type=='02'?'tunnel':'stage');
            let roadStatus = status;
            return require(`@/assets/map_label/${roadName}-${roadStatus}.png`)
        },
        //添加路段
        createRoad({ id, name, lng, lat,type,status }) {
            // 创建一个 Icon
            var startIcon = new AMap.Icon({
                // 图标尺寸
                size: new AMap.Size(34, 43),
                image: this.roadIcon,
                imageSize: new AMap.Size(34, 43)
            });
            var marker = new AMap.Marker({
                map: this.map,
                markerId: id,
                position: [lng, lat],
                icon: startIcon,
                offset: new AMap.Pixel(-17, -40),
                zIndex: 1000
            });
            marker.setLabel({
                direction: 'top',
                offset: new AMap.Pixel(0, 0),
                content: `<div class='road_info'>${name}</div>`
            });
            //鼠标点击marker弹出自定义的信息窗体
            marker.on('click', ()=>{
                let statusContent = status=='超时'?`<p class="desc" style="color:#d84447" >施工状态：${status}</p>`:`<p class="desc">施工状态：${status}</p>`;
                var infoWindow = new AMap.InfoWindow({
                    position: [lng,lat],
                    offset: new AMap.Pixel(0, -50),
                    content: `<div>
                            <h3 class="title" style="color:#d84447">${name}</h3>
                            <p class="desc">路段名称：${name}</p>
                            <p class="desc">路段类型：${type=='01'?'互通':(type=='02'?'隧道':'特殊路段')}</p>
                            ${statusContent}
                        </div>`
                });
                infoWindow.open(this.map);
            });
            this.labelMarkerList.push(marker);
            this.map.setFitView();
        },
        //搜索城市
        searchCity() {
            //区域重点
            let { area } = this.userArea;
            let areaBox = area ? area.split('/') : [];
            let city = areaBox[areaBox.length - 1];
            if (city == '全国' || !area) return false;
            AMap.plugin('AMap.DistrictSearch', () => {
                var districtSearch = new AMap.DistrictSearch({
                    // 关键字对应的行政区级别，共有5种级别
                    level: 'province',
                    // 是否显示下级行政区级数，1表示返回下一级行政区
                    subdistrict: 0,
                    // 返回行政区边界坐标点
                    extensions: 'all'
                });

                districtSearch.search(city, (status, result) => {
                    // 查询成功时，result即为对应的行政区信息
                    if (status == 'complete') {
                        let { districtList } = result;
                        let bounds = districtList[0].boundaries;
                        if (bounds) {
                            const path = [];
                            for (let i = 0, l = bounds[0].length; i < l; i++) {
                                let item = bounds[0][i];
                                let point = [item.lng, item.lat];
                                path.push(point);
                            }
                            var polygon = new AMap.Polygon({
                                path: path,
                                strokeColor: '#0069CA',
                                strokeWeight: 3,
                                strokeOpacity: 0.7,
                                fillOpacity: 0.3,
                                fillColor: '#0069CA',
                                zIndex: 1
                            });
                            this.map.add(polygon);
                            // 缩放地图到合适的视野级别
                            this.map.setFitView([polygon]);
                        }
                    }
                });
            });
        },
        //获取施工地图
        async getMapList(filterStatus = '') {
            try {
                let userId = this.userId;
                let city = this.city;
                let res = await getMapStatistics({ userId, status: filterStatus, city });
                let { data } = res;
                let roadList = [];
                data.map(item => {
                    let {
                        id,
                        workingSection,
                        startStationId,
                        workingStatus,
                        startStationName,
                        startStationLatitude,
                        startStationLongitude,
                        endStationId,
                        endStationName,
                        endStationLatitude,
                        endStationLongitude,
                        rodeType
                    } = item;
                    let roadIndex = roadList.findIndex(road => road.name == workingSection);
                    let status = 'unstart';
                    switch (workingStatus) {
                        case '未施工':
                            status = 'unstart';
                            break;
                        case '施工中':
                            status = 'doing';
                            break;
                        case '超时':
                            status = 'timeout';
                            break;
                        case '待整改':
                            status = 'unrectify';
                            break;
                        case '已完成':
                            status = 'complete';
                            break;
                        default:
                            status = 'unstart';
                    }
                    /**开始坐标 */
                    let startInfo = {
                        name: startStationName,
                        id: startStationId,
                        lng: startStationLongitude,
                        lat: startStationLatitude,
                        type: rodeType,
                        status: status
                    };
                    let endInfo = {
                        name: endStationName,
                        id: endStationId,
                        lng: endStationLongitude,
                        lat: endStationLatitude,
                        status: status,
                        type: rodeType
                    };
                    this.createMarker({ ...startInfo });
                    this.createMarker({ ...endInfo });
                    // 不存在路段
                    if (roadIndex == -1) {
                        // this.createRoad({
                        //     id,
                        //     name: workingSection,
                        //     lng: endStationLongitude - 0.003,
                        //     lat: endStationLatitude - 0.003,
                        //     type:rodeType,
                        //     status:workingStatus
                        // });
                        roadList.push({
                            id: id,
                            name: workingSection,
                            position: [startStationLongitude - 0.003, startStationLatitude - 0.003],
                            lng: startStationLongitude,
                            lat: startStationLatitude,
                            children: [
                                {
                                    startInfo,
                                    endInfo
                                }
                            ]
                        });
                    } else {
                        roadList[roadIndex].children.push({
                            startInfo,
                            endInfo
                        });
                    }
                });
                this.roadList = roadList;
            } finally {
            }
        },
        //获取路标名称的数字进行排序
        getLabelNameCount(name) {
            let start = 1;
            let end = name.indexOf('+');
            let labelNumber = name.substring(start, end);
            let labelCount = name.substring(end + 1);
            return {
                number: labelNumber,
                count: labelCount
            };
        },
        // 基本统计信息
        async getBaseInfo() {
            try {
                let userId = this.userId;
                let res = await getStatistics({ userId });
                this.baseInfo = res.data;
            } finally {
            }
        },
        filterOption(input, option) {
            return option.componentOptions.children[0].dictValue.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        //获取高德天气
        async getAmapWeather() {
            let cityInfo = await axios.get('https://restapi.amap.com/v3/ip', {
                params: { key: this.key }
            });
            let { adcode } = cityInfo.data;
            let weatherInfo = await axios.get('https://restapi.amap.com/v3/weather/weatherInfo', {
                params: { key: this.key, city: adcode }
            });
            let { lives } = weatherInfo.data;
            let liveWeather = lives[0];
            this.liveWeather = liveWeather;
        }
    },
    beforeDestroy() {
        this.map.destroy();
        this.map = null;
        clearTimeout(this.timer);
    }
}
</script>
<style lang="scss">
.road_label_marker {
    position: relative;
    // width: 100px;
    .location{
        width: 36px;
        height: 52px;
    }
    .marker_item {
        position: absolute;
        height: 28px;
        right: 28px;
        top: 10px;
        font-size: 12px;
        font-weight: bold;
        padding: 0 10px;
        // text-align: center;
        box-sizing: border-box;
        // box-shadow: 0 0 2px 2px rgba($color: #000000, $alpha: 0.1);
        p {
            // color: #04a585;
            line-height: 28px;
        }

        // .arrow {
        //     position: absolute;
        //     left: 50%;
        //     transform: translateX(-50%);
        //     bottom: -10px;
        //     width: 0;
        //     height: 0;
        //     border-left: 10px solid transparent;
        //     border-right: 10px solid transparent;
        // }
    }

    &.unstart {
        color: #e1cb07;
        // .marker_item {
        //     background-color: #e1cb07;

        //     & > .arrow {
        //         border-top: 10px solid #e1cb07;
        //     }
        // }
    }

    &.doing {
        color: #098a75;
        // .marker_item {
        //     background-color: #04a585;

        //     .arrow {
        //         border-top: 10px solid #04a585;
        //     }
        // }
    }

    &.timeout {
        color: #b5473f;
        // .marker_item {
        //     background-color: #f75444;

        //     .arrow {
        //         border-top: 10px solid #f75444;
        //     }
        // }
    }

    &.unrectify {
        color: #e3711e;
        // .marker_item {
        //     background-color: #ff9c1d;

        //     .arrow {
        //         border-top: 10px solid #ff9c1d;
        //     }
        // }
    }

    &.complete {
        color: #1a80dc;
        // .marker_item {
        //     background-color: #1a80dc;

        //     .arrow {
        //         border-top: 10px solid #1a80dc;
        //     }
        // }
    }
}
</style>
<style lang="scss" scoped>
::v-deep .amap-marker-label {
    padding: 4px 8px;
    border-color: #054faa;
    color: #fff;
    background: #054faa;
    border-radius: 4px;
}
.map_right_side {
    position: absolute;
    right: 0;
    top: 20px;
    z-index: 101;
    align-items: flex-end;
    justify-content: flex-end;
    .side_item {
        width: 120px;
        padding: 8px 10px;
        margin-top: 10px;
        font-size: 12px;
        color: #fff;
        align-items: center;
        background-color: #011d3f;
        cursor: pointer;
        .info {
            flex: 1;
            line-height: 1.2;
        }
    }
}
.city_modal {
    padding: 10px 20px;
    background: #011d3f;
}
.menu_box {
    position: absolute;
    right: 80px;
    bottom: 20px;
    z-index: 98;

    .menu_item {
        justify-content: center;
        align-items: center;
        margin: 0 10px;
        cursor: pointer;
        opacity: 0.5;

        &.active {
            opacity: 1;
        }
        .icon {
            width: 40px;
            height: 40px;
        }
        .label {
            margin-top: -13px;
            width: 100%;
            padding: 2px 0;
            text-align: center;
            font-size: 12px;
            color: #fff;
            background: rgba($color: #305695, $alpha: 0.7);
            border: 1px solid #375885;
            border-radius: 4px;
        }
    }
}

.statistics_box {
    position: absolute;
    left: 0;
    top: 20px;
    z-index: 99;
    background: rgba($color: #003678, $alpha: 0.7);
    border-radius: 6px;
    box-shadow: 0 2px 2px 2px rgba($color: #000000, $alpha: 0.1);

    .statistic_item {
        border-right: 1px solid rgba($color: #888b8c, $alpha: 0.4);
        align-items: center;
        max-width: 150px;
        padding: 16px 25px;

        .icon {
            width: 40px;
            height: 40px;
            flex-shrink: 0;
        }

        .content {
            margin-left: 10px;
            color: #fff;
            justify-content: center;
            font-size: 12px;

            span {
                width: 100px;
            }

            .num {
                margin-bottom: 5px;
                font-size: 16px;
                font-weight: bold;
            }
        }
    }
}

.supervision_map,
.super_amap {
    position: relative;
    flex: 1;
    overflow: hidden;
    ::v-deep .ant-spin-container {
        display: flex;
        flex: 1;
        flex-direction: column;
    }

    & > ::v-deep .el-vue-amap {
        display: flex;
        flex: 1;
    }
}
</style>
